local FeederCtl = {}

local IO_START = 1
local IO_STOP = 2

local Feeder = require("feeder")

local function onBtnStartClick()
    gpio.trig(IO_START)
    if not Feeder.isRunning() then
        Feeder.start()
    end
    tmr.create():alarm(500, tmr.ALARM_SINGLE, function()
        gpio.trig(IO_START, "up", onBtnStartClick)
    end)
end

local function onBtnStopClick()
    gpio.trig(IO_STOP)
    if Feeder.isRunning() then
        Feeder.stop()
    end
    tmr.create():alarm(500, tmr.ALARM_SINGLE, function()
        gpio.trig(IO_STOP, "up", onBtnStopClick)
    end)
end

function FeederCtl.init(checkDelay, feedTime)
    gpio.mode(IO_START, gpio.INT)
    gpio.mode(IO_STOP, gpio.INT)

    gpio.write(IO_START, gpio.LOW)
    gpio.write(IO_STOP, gpio.LOW)

    Feeder.init(checkDelay, feedTime)

    gpio.trig(IO_START, "up", onBtnStartClick)
    gpio.trig(IO_STOP, "up", onBtnStopClick)
end

function FeederCtl.feed()
    if not Feeder.isRunning() then
        Feeder.feed()
    end
end

function FeederCtl.getFeedTimes()
    return Feeder.getFeedTimes()
end

function FeederCtl.start()
    Feeder.start()
end

function FeederCtl.stop()
    Feeder.stop()
end

return FeederCtl
